
function layerInit(){
    clearStatus();
    //初始化多选图片组件
    var selectSkuObj = $("#select-sku");
    var checkSku = selectSkuObj.comCheck();
    selectSkuObj.on('change',"input[type='checkbox']",function(){
        $("[name='skuList']").val(checkSku.checked().join(','));
        getCheckedPrice();
        //p.data.skuList = checkSku.checked();
    });

    //初始化日期组件
    $('.J-datepicker-range-day').datePicker({
        hasShortcut: true,
        format: 'YYYY-MM-DD',
        isRange: true,
        shortcutOptions: [
            {
                name: 'One week later',
                day: '0,7'
            }, {
                name: 'After one month',
                day: '0,30'
            },{
                name: 'After three month',
                day: '0,90'
            }]
    });
    //设置默认日期
    setTimeout(function(){
        setTime();
    },200);



    var accordionObj = $(".order-box");
    var orderList = accordionObj.find(".box-list");
    var currentObj = null;
    p.isMenu = (orderList && orderList.length) ? true : false;

    //离开输入订单焦点事件
    $("[name='orderNo']").on('blur',function(){
        clearStatus();
        var isTrue = false;
        var id = $(this).val();
        orderList.each(function(index,item){
            var currentId = $(item).find("#orderNo").html();
            if(id == currentId){
                currentObj = $(item);
                isTrue = true;
                return false;
            }
        })

        if(p.isMenu && isTrue){
            //若能拿到产品列表对象
            renderMenuArr(currentObj);
            renderList();
            //渲染币种符号
            fillInput();
        }else{
            reqOrder();
        }

    });

    //初始化渲染checked模板
    if(!p.isMenu){
        reqOrder();
    }else if(orderList.length==1){
        currentObj = orderList;
        renderMenuArr(currentObj);
        renderList();
        $("[name='orderNo']").val(currentObj.find("#orderNo").html());
        fillInput();
    }

    //请求原因列表
    renderReason();

    //请求币种列表
    renderCurrency();


    $("#form").validate({
        rules: {
            orderNo:{required:true,},
            amount:{required:true,},
            currencyCode:{required:false,},
        },
        messages: {
            orderNo:{required:'Please enter the order number！',},
            amount:{required:'Please fill in the coupon code amount！',},
            currencyCode:{required:'Please select a currency!',},
        },
    });

}

function fillInput(){
    var currency = "";
    if(p.isMenu){
        currency = $("#currencyName").eq(0).html();
    }else{
        currency = p.currency;
    }
    $("#currencySymbol").html(currency);
}

//渲染图片选择列表
function renderList(){
    var tmpCheck = $("#tmpCheckList").clone();
    var str = "";
    $.each(p.skuArr,function(index,item){
        var src = item.src;
        var sku = item.sku;
        var price = item.price;
        tmpCheck.find("img").prop('src',src);
        tmpCheck.find(".img-sku").html(sku);
        tmpCheck.find("[type='checkbox']").val(sku);
        tmpCheck.find("[data-name='price']").attr("data-price",numberSplit(price));
        str += tmpCheck.html();
    });
    $("#select-sku").html(str);
}

//根据订单渲染
function renderMenuArr(currentObj){
    clearStatus();
    var list = currentObj.find(".content-list");
    list.each(function(index,item){
        var obj = {};
        obj.src = $(item).find('img').prop('src');
        obj.sku = $(item).find('.skuId').html();
        obj.price = $(item).find(".productPrice").html();
        p.skuArr.push(obj)
    });
}


function numberSplit(s){
    s = s.toString();
    var num = s.replace(/^([a-zA-Z])*/,"");
    return num;
}

//获取勾选的价格
function getCheckedPrice(){
    var price = 0;
    $("#select-sku").find('label').each(function(index,item){
        var isTrue = $(item).find(":checkbox").prop('checked');
        if(isTrue){
            price+=Number($(this).attr('data-price'));
        }
    });
    $("#checkedPriceTotal").html(price.toFixed(2));
}

//清除
function clearStatus(){
    p.skuArr = [];
    $("[name='skuList']").val('');
    $("#select-sku").html('');
    $("[name='startTime']").val('');
    $("[name='endTime']").val('');
}

//渲染创建的原因列表
function renderReason(){
    app.ajax({
        type:'get',
        url:app.api('/api/coupon/getSearchSelect'),
        success:function(res){
            if(res.code == 0){
                //初始化级联
                $('.com-select-floor').comSelectFloor({
                    data:filterReason(res.data.reasonId),
                    multi:true,
                    callback:function(val,text){}
                });
            }
        }
    })
}

//更改原因字段
function filterReason(reasonArr){
    var arr = [];
    $.each(reasonArr,function(index,item){
        var obj = {
            label:item.Name,
            value:item.Id,
            children:[]
        }
        if(item.ChildProblemData && item.ChildProblemData.length>=1){
            obj.children = filterReason(item.ChildProblemData)
        }
        arr.push(obj);
    });
    return arr;
}

//渲染币种
function renderCurrency(){
    var currency = $("#currencyName").html();
    var d = JSON.stringify({
        "siteId": p.siteId
    });
    app.ajax({
        type:'post',
        url:app.api('/api/coupon/getCurrencyCodeListBySiteId'),
        data:d,
        success:function(res){
            if(res.code == 0){
                var str = "";
                var currencyObj = res.data;
                $.each(currencyObj,function(index,item){
                    str+= "<option value='"+item+"'>"+item+"</option>";
                });
                $("select[name='currencyCode']").html(str);

                //渲染默认币种
                $("[name='currencyCode']").val(currency);
            }
        }
    })
}


//请求优惠券 创建
function requestCoupon(btnObj){
    var d = JSON.stringify(getPara());
    app.ajax({
        type:'post',
        url:app.api('/api/coupon/create'),
        data:d,
        success:function(res){
            if(res.code == 0){
                p.code = res.data;
                $.comMessage({  //可选(warning/success/prompt)
                    type:'prompt',
                    text:res.message,
                });
                p.quill.focus();
                p.quill.insertText(0, p.code, 'bold', false);
                //$("#code-coupon").val(p.code);
                p.layerObj.close();
            }else{
                $.comMessage({  //可选(warning/success/prompt)
                    type:'prompt',
                    text:res.message,
                });
            }
        },
        complete:function(){
            btnObj.removeClass('active-animate').prop('disabled',false);
        }
    })
}
//获取列表参数
function getPara(){
    $.each($("#form").serializeArray(),function(index,item){
        p.coupon[item.name] = item.value;
    });
    p.coupon.siteId = p.siteId;
    p.coupon.createById = para.user.admin_id;
    p.coupon.createByMail = para.user.admin_username;
    p.coupon.createByName = para.user.admin_nickname;
    p.coupon.orderUserId = -1;
    p.coupon.orderUserMail = p.receiver_email;

    return p.coupon;
}

//设置时间
function setTime(){
    var t = new Date().getTime();
    var oldTime = t + 86400*90*1000;
    var end = com.formatDate(oldTime,'-').split(' ')[0];
    var start = com.formatDate(t,'-').split(' ')[0];
    $("input[name='startTime']").val(start);
    $("input[name='endTime']").val(end);
}


function reqOrder(){
    var siteId =  p.siteId; //384143
    var order = $("input[name='orderNo']").val();//1
    if(siteId && order){
        $.ajax({
            type:'get',
            url:app.api('/api/callcenter/packageList/'+order+'/' + siteId),
            success:function(res){
                if(res.code == 0){
                    var arr = res.data[0].PackageList[0].goodsList;
                    $.each(arr,function(index,item){
                        var obj = {};
                        obj.src = item.ThumbnailsUrl;
                        obj.sku = item.SkuId;
                        obj.price = item.CurrencyPrice;
                        p.skuArr.push(obj)
                    });
                    renderList();
                    p.currency = res.data[0].currency;
                    fillInput();
                }else{
                    $.comMessage({  //可选(warning/success/prompt)
                        type:'prompt',
                        text:'订单号不存在！',
                    })
                    clearStatus();
                }
            },
            error:function(){
                $.comMessage({  //可选(warning/success/prompt)
                    type:'error',
                    text:res.msg,
                });
                clearStatus();
            }
        })
    }else{
        clearStatus();
    }

}